package com.ruben.simplescaffold.plugin;

import cn.hutool.core.collection.CollUtil;
import com.ruben.simplescaffold.entity.UserDetail;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * @author <achao1441470436@gmail.com>
 * @since 2022/4/10 21:40
 */
@Component
@Intercepts(@Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class}))
public class MybatisResultSetHandlerHandleResultSetsPlugin implements Interceptor {
	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		List<?> resultList = (List<?>) invocation.proceed();
		Object bean = CollUtil.get(resultList, 0);
		if (bean instanceof UserDetail) {
			@SuppressWarnings("unchecked")
			ArrayList<UserDetail> userList = (ArrayList<UserDetail>) resultList;
			userList.forEach(user -> user.setPassword(null));
			return userList;
		}
		return resultList;
	}

	@Override
	public Object plugin(Object target) {
		return Plugin.wrap(target, this);
	}
}
